#ifdef USE_SQL
#include <string.h>

#include "lib.h"
#include "warserv.h"
#include "warconn.h"
#include "warhand.h"
#include "warsql.h"
#include "warsaved.h"
#include "wargame.h"
#include "warproto.h"
#include "stdncerr.h"
#include "opts.h"
#include "log.h"
#include "badpacketmsgs.h"
#include "XMLTranslator.h"

static WarSQL* tracker = (WarSQL*)0;

typedef struct _info
{
	String			login;
	PID				pid;
	SESSIONID		sessionId;
	WarGameID		gid;
	bool8			forMoney;
} Info, *pInfo;

void
WarServer::startTracker()
{
	ServerOpts::load();

	tracker = new WarSQL(ServerOpts::dbdsn,
		ServerOpts::dblogin, ServerOpts::dbpasswd);

	// CSN-8891
	webServiceCall = new WebServiceCall();
}

void
WarServer::stopTracker()
{
	delete tracker;
	tracker = 0;

	delete webServiceCall;
	webServiceCall = 0;
}

bool8
WarServer::initSuccess()
{
	if (tracker && tracker->initOK())
		return Server::initSuccess();
	else
	{
		Log::msgError("Failed to connect to the database.  Aborting.");
		return false;
	}
}


bool8
WarConnection::parseCasinoLogin(int32 stdReq, int32* Err)
{
	Info* info;
	int32 i;

	if (msgbuf[1]	!= APP1				|| msgbuf[2] != APP2 ||
		msgbuf[3]	!= PROTO_VERSION1	|| msgbuf[4] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		DEBUGMSG(("Login: incorrect version: %c%c  ",
				msgbuf[1],msgbuf[2],msgbuf[3],msgbuf[4]));
		return false;
	}

	info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	i = stdReq;

	char login[PIDLEN + 1];
	memcpy(login, msgbuf + i, PIDLEN);
	login[PIDLEN] = '\0';
	i += PIDLEN;

	strlwr(login);
	info->login = login;

	info->forMoney = (bool8)(msgbuf[i++] != 0);

	// CSN-10426: with this modification, we don't need iClientID sent by the client, so we skip it
	String sClientTypeIntAPI = String::emptyString;
	i++;	// Skip ClientID

	if (xmlTranslator && xmlTranslator->UsingFunPID())
	{
		// CSN-7076: New Authentication (fun play)
		bool8 result;
		tracker->lock();
		result = tracker->getAvailableFunID( info->login );
		tracker->unlock();
		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}
	else
	{			
		// CSN-7075: New Authentication
		String sToken = String::emptyString;
		i =+ sToken.deserialize(&msgbuf[i]);
		
		// CSN-8909: Look for clientType in Integration API
		if (!wsCall()->Authenticate(sToken, info->login, sClientTypeIntAPI, m_sCurrency))
		{
			bool8 bAuth = false;
			
			// CSN-12167: connect with no token? In that case, white-listed PID is sent in <Token> field
			#ifdef DEBUGSPIN
			if (ServerOpts::bAllowTesting)
			{
				bAuth = tracker->isFreeFromAuthentication(sToken);					
				if (bAuth)
					info->login = sToken;
			}
			#endif

			if (!bAuth)
			{
				*Err = LOGINERR_CONTACTCUSTSERVICE;
				delete info;
				info = 0;
				return false;
			}
		}
	}

	if (tracker)
	{
		int32 result;

		tracker->lock();
		//result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		result = tracker->createRTGSession(info->forMoney, info->login, info->sessionId, sClientTypeIntAPI);
		tracker->unlock();

		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}

	info->pid = info->login;

	#ifdef FORCEDSHOE       //RPF 20100317 When forcing the shue now filter by pid
	m_pid = info->login;
    #endif

	/*
	if (tracker)
	{
		int32 result = WarSQL::ExecFailed;

		tracker->lock();
		result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		tracker->unlock();

        if (result != WarSQL::NoError)
        {
			if(result == WarSQL::AdminLogout)
				*Err = LOGINERR_ADMINLOGOUT;
			else if(result == WarSQL::AutoLogout)
				*Err = LOGINERR_AUTOLOGOUT;
			else
				*Err = LOGINERR_NOTLOGGEDIN;

            DEBUGMSG(("Login: attempt to play without logging in: %S",
                (const uint16*) info->login));
            delete info;
            return false;
        }
	}
	*/

	memset(info->gid, 0xff, sizeof(WarGameID));

	casinoSpecific = info;

	return true;
}



bool8
WarConnection::parseUnicodeCasinoLogin(int32 stdReq, int32* Err)
{
	Info* info;
	int32 i;

	if (msgbuf[2]	!= APP1				|| msgbuf[3] != APP2 ||
		msgbuf[4]	!= PROTO_VERSION1	|| msgbuf[5] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		DEBUGMSG(("Login: incorrect version: %c%c  ",
				msgbuf[2],msgbuf[3],msgbuf[4],msgbuf[5]));
		return false;
	}

	info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	i = stdReq;

	i += info->login.deserialize(msgbuf + i);
	info->login.toLower();

	info->forMoney = (bool8)(msgbuf[i++] != 0);

	// CSN-10426: with this modification, we don't need iClientID sent by the client, so we skip it
	String sClientTypeIntAPI = String::emptyString;
	i++;	// Skip ClientID

	if (xmlTranslator && xmlTranslator->UsingFunPID())
	{
		// CSN-7076: New Authentication (fun play)
		bool8 result;
		tracker->lock();
		result = tracker->getAvailableFunID( info->login );
		tracker->unlock();
		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}
	else
	{			
		// CSN-7075: New Authentication
		String sToken = String::emptyString;
		i =+ sToken.deserialize(&msgbuf[i]);
		
		// CSN-8909: Look for clientType in Integration API
		if (!wsCall()->Authenticate(sToken, info->login, sClientTypeIntAPI, m_sCurrency))
		{
			bool8 bAuth = false;
			
			// CSN-12167: connect with no token? In that case, white-listed PID is sent in <Token> field
			#ifdef DEBUGSPIN
			if (ServerOpts::bAllowTesting)
			{
				bAuth = tracker->isFreeFromAuthentication(sToken);					
				if (bAuth)
					info->login = sToken;
			}
			#endif

			if (!bAuth)
			{
				*Err = LOGINERR_CONTACTCUSTSERVICE;
				delete info;
				info = 0;
				return false;
			}
		}
	}

	if (tracker)
	{
		int32 result;

		tracker->lock();
		//result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		result = tracker->createRTGSession(info->forMoney, info->login, info->sessionId, sClientTypeIntAPI);
		tracker->unlock();

		if (!result)
		{
			*Err = LOGINERR_CONTACTCUSTSERVICE;
			delete info;
			info = 0;
			return false;
		}
	}

	info->pid = info->login;

	#ifdef FORCEDSHOE       //RPF 20100317 When forcing the shue now filter by pid
	m_pid = info->login;
    #endif

	/*
	if (tracker)
	{
		int32 result = WarSQL::ExecFailed;

		tracker->lock();
		result = tracker->validateLogin(info->login, info->sessionId, info->pid);
		tracker->unlock();

        if (result != WarSQL::NoError)
        {
			if(result == WarSQL::AdminLogout)
				*Err = LOGINERR_ADMINLOGOUT;
			else if(result == WarSQL::AutoLogout)
				*Err = LOGINERR_AUTOLOGOUT;
			else
				*Err = LOGINERR_NOTLOGGEDIN;

            DEBUGMSG(("Login: attempt to play without logging in: %S",
                (const uint16*) info->login));
            delete info;
            return false;
        }
	}
	*/

	memset(info->gid, 0xff, sizeof(WarGameID));

	casinoSpecific = info;

	return true;
}

void
WarConnection::removeCasinoSpecific()
{
	delete (pInfo)casinoSpecific;

	casinoSpecific = (void*)0;
}

int32
WarConnection::encode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
WarConnection::decode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

bool8
WarConnection::trackGetBalance( int32 *balance )
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;
	int32 comp;
	*balance = 0;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->getBalance(ServerOpts::casinoId,
			info->pid, info->forMoney, balance, &comp);
		tracker->unlock();
	}

	return (bool8)(result == WarSQL::NoError);
}

int32
WarConnection::trackAdjustBalance(int32 Amount)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;
	int32 bal=0, comp=0;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->adjustBalance(ServerOpts::casinoId,
			info->pid, info->forMoney,
			Amount, &bal, &comp);
		tracker->unlock();
	}

	if (result == WarSQL::NoError)
		return bal;
	return 0;
}

bool8
WarConnection::trackGetPlayerLimits(int32* minBet, int32* maxBet,
	int32* compFactor)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->getPlayerLimits(info->pid, GAMEID, MACHID,
			minBet, maxBet, compFactor);
		tracker->unlock();
	}

	return (bool8)(result == WarSQL::NoError);
}

bool8
WarConnection::trackNewGame(int32 Bet, int32 *Balance)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;
	int32 comp;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->createGame(ServerOpts::casinoId,
			info->pid, info->forMoney,
			info->sessionId, info->forMoney ? compFactor : 0,
			info->gid, Bet, Balance, &comp);
		tracker->unlock();
	}

	return (bool8)(result == WarSQL::NoError);
}


bool8
WarConnection::trackDeal(WarHand* Dealer, WarHand* Player)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->deal(info->pid, info->gid,
			1, Dealer->getCardAt(0),
			1, Player->getCardAt(0),
			false);
		tracker->unlock();
	}
	return (bool8)(result == WarSQL::NoError);
}

bool8
WarConnection::trackRaise(WarHand* Dealer, WarHand* Player)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->deal(info->pid, info->gid,
			1, Dealer->getCardAt(1),
			1, Player->getCardAt(1),
			true);
		tracker->unlock();
	}
	return (bool8)(result == WarSQL::NoError);
}

bool8
WarConnection::trackGameDone(bool8 Raised, bool8 NoWar,
	int32 PayAnte, int32 PayRaise,
	int32 Outcome, int32 BalAdjust, int32 *Balance)
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;
	int32 comp;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->gameDone(ServerOpts::casinoId,
			info->pid, info->forMoney, info->gid,
			Raised, NoWar, PayAnte, PayRaise, Outcome,
			BalAdjust, Balance, &comp);
		tracker->unlock();
	}

	return (bool8)(result == WarSQL::NoError);
}

bool8	
WarConnection::trackHasSavedGame()
{
	pInfo info = (pInfo)casinoSpecific;
	WarSavedGame sg;
	bool8 exists;
	int32 result = WarSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = ((WarSQL*)tracker)->hasSavedGame(info->pid, info->forMoney,
			info->gid, &sg, &exists);
		if (result == WarSQL::NoError)
		{
			if (exists)
			{
				game = new WarGame(this, &sg);
			}
			else
			{
				memset(info->gid, 0xff, sizeof(WarGameID));
			}
		}
		tracker->unlock();
	}
	return (bool8)(result == WarSQL::NoError);
}

bool8
WarConnection::trackRemoveSavedGame()
{
	pInfo info = (pInfo)casinoSpecific;
	int32 result = WarSQL::ExecFailed;

	if (tracker && info)
	{
		tracker->lock();
		result = tracker->removeSavedGame(info->pid, info->forMoney);
		tracker->unlock();
	}
	
	return (bool8)(result == WarSQL::NoError);
}

bool8
WarConnection::trackSaveGame()
{
	pInfo info = (pInfo)casinoSpecific;
	WarSavedGame sg;
	int32 result = WarSQL::ExecFailed;

	if (!game)
		return true;

	if (tracker && info)
	{
		game->save(&sg);

		tracker->lock();
		result = tracker->saveGame(info->pid, info->forMoney, info->gid, &sg);
		tracker->unlock();

		return (bool8)(result == WarSQL::NoError);
	}
	return false;
}

void
WarConnection::trackaddBadPacket(int32 error_reason, char MessageType, char *msgbuf, int32 msglen)
{
	pInfo info = (pInfo)casinoSpecific;

	if (tracker && info)
	{
		tracker->lock();
		tracker->addBadPacket(GAMEID, MACHID, sBadPacketMessages[error_reason].message, sBadPacketMessages[error_reason].severity, info->pid, MessageType, (uint8*)msgbuf, msglen);
		tracker->unlock();
	}
}

int32
WarConnection::trackValidateLogin()
{
    pInfo info = (pInfo)casinoSpecific;
    int32 result = WarSQL::ExecFailed;

    if (tracker && info)
    {
        tracker->lock();
		result = tracker->validateLogin(info->login, info->sessionId, info->pid);
        tracker->unlock();
    }

    return result;
}

int32
WarConnection::trackValidateSession()
{
    pInfo info = (pInfo)casinoSpecific;
    int32 result = WarSQL::ExecFailed;

    if (tracker && info)
    {
        tracker->lock();
		result = tracker->validateSession(info->pid, info->sessionId);
        tracker->unlock();
    }

    return result;
}

void WarConnection::trackLogoutSession()
{
    pInfo info = (pInfo)casinoSpecific;

	if (tracker && info && !info->login.isEmpty())
    {
        tracker->lock();
		tracker->logout(ServerOpts::casinoId, info->login, info->forMoney, String::emptyString, info->sessionId);
        tracker->unlock();
    }
}

#else	// USE_SQL

#include <string.h>

#include "lib.h"
#include "warserv.h"
#include "warconn.h"
#include "warver.h"
#include "stdncerr.h"

#define APP1		(uint8)'W'
#define APP2		(uint8)'R'

typedef struct _info
{
	int32 balance;
} Info, *pInfo;

void WarServer::startTracker() { }
void WarServer::stopTracker() { }
bool8 WarServer::initSuccess() { return Server::initSuccess(); }
void WarConnection::trackaddBadPacket(int32 error_reason, char MessageType, char *msgbuf, int32 msglen) {}

bool8
WarConnection::parseCasinoLogin(int32 /*stdReq*/, int32* Err)
{
	if (msgbuf[1]	!= APP1				|| msgbuf[2] != APP2 ||
		msgbuf[3]	!= PROTO_VERSION1	|| msgbuf[4] != PROTO_VERSION2)
	{
		*Err = LOGINERR_BADVERSION;
		return false;
	}

	Info* info = new Info();
	if (!info)
	{
		*Err = LOGINERR_TRYLATER;
		return false;
	}

	info->balance = 100000;		// $1000.00 to start with

	casinoSpecific = info;

	return true;
}
void
WarConnection::removeCasinoSpecific()
{
	delete (pInfo)casinoSpecific;

	casinoSpecific = (void*)0;
}

int32
WarConnection::encode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
WarConnection::decode(uint8* In, uint8* Out, int32 Len)
{
	memcpy(Out, In, Len);
	return Len;
}

int32
WarConnection::trackGetBalance()
{
	pInfo info = (pInfo)casinoSpecific;
	if (info)
		return info->balance;
	else
		return 0;
}

int32
WarConnection::trackAdjustBalance(int32 Amount)
{
	pInfo info = (pInfo)casinoSpecific;
	if (info)
	{
		info->balance += Amount;

		return info->balance;
	}
	else
		return 0;
}

bool8
WarConnection::trackNewGame(int32 Bet, int32* Balance)
{
	pInfo info = (pInfo)casinoSpecific;

	if (info)
		*Balance = trackAdjustBalance(-Bet);
	else
		*Balance = 0;

	return true;
}

bool8
WarConnection::trackDeal(WarHand* /*Dealer*/, WarHand* /*Player*/)
{
	return true;
}

bool8
WarConnection::trackGameDone(bool8 /*Raised*/,
	int32 /*PayAnte*/, int32 /*PayRaise*/, int32 /*Outcome*/,
	int32 BalAdjust, int32 *Balance)
{
	pInfo info = (pInfo)casinoSpecific;

	if (info)
		*Balance = trackAdjustBalance(BalanceAdjust);
	else
		*Balance = 0;

	return true;
}

bool8 WarConnection::trackHasSavedGame(int32* /*err*/) { return false; }
bool8 WarConnection::trackSaveGame() { return true; }

#endif
